package com.shfl.task.listener;

import cn.hutool.core.date.DateUtil;
import com.shfl.task.logic.constants.CommonConstants;
import com.shfl.task.logic.model.info.TaskLogInfo;
import com.shfl.task.logic.service.TaskLogService;
import org.quartz.*;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 * 任务监听器
 */
public class MyJobListener implements JobListener {

    private TaskLogService taskLogService;

    private SchedulerFactoryBean schedulerFactoryBean;

    public MyJobListener(SchedulerFactoryBean schedulerFactoryBean, TaskLogService taskLogService) {
        this.schedulerFactoryBean = schedulerFactoryBean;
        this.taskLogService = taskLogService;
    }

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    /**
     * 在Job将要被执行时调用这个方法
     *
     * @param jobExecutionContext 任务详情
     */
    @Override
    public void jobToBeExecuted(JobExecutionContext jobExecutionContext) {

    }

    /**
     * 在Job即将被执行，但却被 TriggerListerner监听器的 vetoJobExecution（）方法否决时 执行
     * 也就是该执行时，但却未执行时调用
     *
     * @param jobExecutionContext 任务详情
     */
    @Override
    public void jobExecutionVetoed(JobExecutionContext jobExecutionContext) {
        Trigger trigger = jobExecutionContext.getTrigger();
        TaskLogInfo taskLog = new TaskLogInfo();
        taskLog.setTaskId(Long.valueOf(trigger.getKey().getName()));
        taskLog.setLastTime(trigger.getNextFireTime().getTime());
        taskLog.setTaskStatus(CommonConstants.TaskLogStatus.MISS.getCode());
        saveLog(taskLog);
    }

    /**
     * 执行结束时调用
     *
     * @param jobExecutionContext 任务详情
     * @param e                   任务异常
     */
    @Override
    public void jobWasExecuted(JobExecutionContext jobExecutionContext, JobExecutionException e) {
        JobDetail jobDetail = jobExecutionContext.getJobDetail();
        Trigger trigger = jobExecutionContext.getTrigger();
        TaskLogInfo taskLog = new TaskLogInfo();
        taskLog.setTaskId(Long.valueOf(trigger.getKey().getName()));
        taskLog.setLastTime(trigger.getNextFireTime().getTime());
        taskLog.setTaskStatus(CommonConstants.TaskLogStatus.SUCCESS.getCode());
        // 出现异常直接删除任务 等待定时任务重新开启
        if (e != null) {
            try {
                schedulerFactoryBean.getScheduler().deleteJob(jobDetail.getKey());
            } catch (SchedulerException e1) {
                e1.printStackTrace();
            }
            taskLog.setLastTime(0L);
            taskLog.setTaskStatus(CommonConstants.TaskLogStatus.FAILURE.getCode());
            taskLog.setErrorContent(e.getMessage());
        }
        saveLog(taskLog);
    }

    private void saveLog(TaskLogInfo taskLog) {
        taskLog.setCreateTime(DateUtil.current());
        taskLogService.insertSelective(taskLog);
    }
}

